<template>
    <div id="user-list">
        <div v-show="showAddOrEdit">
            <router-view></router-view>
        </div>
        <div class="container-fluid" v-show="!showAddOrEdit">
            <div class="panel panel-info">
                <vxe-toolbar custom print export ref="xToolbar" class="panel-heading">
                    <template #buttons>
                        <vxe-button type="text" status="success" icon="fa fa-plus"
                                    v-show="$request.isHavePermissions('/sys/user/add')"
                                    @click="$router.push('/sys/user/add');showAddOrEdit = true;" content="新增">
                        </vxe-button>
                        <vxe-button type="text" status="warning" icon="fa fa-edit"
                                    v-show="$request.isHavePermissions('/sys/user/edit')"
                                    content="修改" @click="edit();"></vxe-button>
                        <vxe-button type="text" status="danger" icon="fa fa-remove"
                                    v-show="$request.isHavePermissions('/sys/user/delete')"
                                    content="删除" @click="del()"></vxe-button>
                        <vxe-button type="text" status="info" icon="fa fa-users"
                                    v-show="$request.isHavePermissions('/sys/userRoles/edit')"
                                    content="额外角色" @click="role()"></vxe-button>
                    </template>
                    <template #tools>
                        <vxe-input v-model="tablePage.searchText" placeholder="请输入关键字" @change="searchTextChange()"
                                   style="margin-right: .8em;"></vxe-input>
                        <vxe-button circle icon="fa fa-refresh" @click="loadData();" :loading="loading"></vxe-button>
                    </template>
                </vxe-toolbar>
                <div class="panel-body" style="padding: 0.125rem;">
                    <vxe-table row-id="id" :loading="loading" :data="list"
                               :checkbox-config="{trigger: 'row', highlight: true, range: true}"
                               :sort-config="{trigger: 'cell', defaultSort: {field: 'id', order: 'desc'}, orders: ['desc', 'asc', null]}"
                               @sort-change="sortChangeEvent4" border show-header-overflow show-overflow
                               highlight-current-row round
                               resizable ref="xTable1" align="center" :filter-config="{remote: true}"
                               @filter-change="filterChangeEvent"
                               :tooltip-config="{showAll: true, enterable: true}" :print-config="{}"
                               :export-config="{}">
                        <vxe-column type="checkbox" width="40" fixed="left"></vxe-column>
                        <vxe-column field="name" title="姓名" sortable :filters="[{ data: '' }]" width="200" fixed="left">
                            <template #filter="{ $panel, column }">
                                <input type="type" class="form-control" placeholder="请输入姓名"
                                       v-for="(option, index) in column.filters"
                                       :key="index" v-model="option.data"
                                       @input="$panel.changeOption($event, !!option.data, option)">
                            </template>
                            <template #default="{row}">
                <span v-show="$request.isHavePermissions('/sys/user/edit')">
                  <a style="color: blue;text-underline: #2e6da4;" href="javascript:void(0);"
                     @click="edit(row.id)">{{ row.name }}</a>
                </span>
                                <span v-show="!$request.isHavePermissions('/sys/user/edit')">{{ row.name }}</span>
                            </template>
                        </vxe-column>
                        <vxe-column field="nick" title="昵称" :filters="[{ data: '' }]" width="200">
                            <template #filter="{ $panel, column }">
                                <input type="type" class="form-control" placeholder="请输入昵称"
                                       v-for="(option, index) in column.filters"
                                       :key="index" v-model="option.data"
                                       @input="$panel.changeOption($event, !!option.data, option)">
                            </template>
                        </vxe-column>
                        <vxe-column field="genderName" title="性别" :filters="[]" width="100"></vxe-column>
                        <vxe-column field="birthday" title="出生日期" :formatter="formatterTime" width="200"></vxe-column>
                        <vxe-column field="address" title="地址" sortable width="300"></vxe-column>
                        <vxe-column field="email" title="邮箱" sortable width="300"></vxe-column>
                        <vxe-column field="roleName" title="主角色" :filters="[]" width="150"></vxe-column>
                        <vxe-column field="createTime" title="创建时间" :formatter="formatterTime" sortable
                                    width="180"></vxe-column>
                        <vxe-column field="updateTime" title="修改时间" :formatter="formatterTime" sortable
                                    width="180"></vxe-column>
                        <vxe-column field="deleteTime" title="删除时间" :formatter="formatterTime" width="180"></vxe-column>
                    </vxe-table>
                    <vxe-pager :loading="loading" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
                               :total="tablePage.totalResult"
                               :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                               @page-change="handlePageChange">
                    </vxe-pager>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: 'SysUserList',
    data () {
        return {
            list: [],
            loading: false,
            tablePage: {
                currentPage: 1,
                pageSize: 4,
                totalResult: 0,
                sortName: 'id',
                sortOrder: 'desc',
                searchText: ''
            },
            filterData: {
                // 筛选数据
            },
            showDetails: false,
            showAddOrEdit: false,
            genders: [],
            roles: []
        }
    },
    created () {
        this.$nextTick(() => {
            // 将表格和工具栏进行关联
            const $table = this.$refs.xTable1
            $table.connect(this.$refs.xToolbar)
        })
        this.loadData()
    },
    mounted () {
        // 加载角色筛选数据
        this.$request.get(this.$apiSys.userRolesUrl).then(res => {
            if (Array.isArray(res)) {
                let roles = []
                for (var i = 0, length1 = res.length; i < length1; i++) {
                    let item = res[i]
                    roles.push({
                        value: item.id,
                        label: item.name
                    })
                }
                this.roles = roles
                const $table = this.$refs.xTable1
                if ($table) {
                    const roleNameColumn = $table.getColumnByField('roleName')
                    if (roleNameColumn) {
                        $table.setFilter(roleNameColumn, this.roles)
                    }
                }
            }
        })
        // 加载性别
        this.$request.get(this.$apiSys.userGendersUrl).then(res => {
            if (Array.isArray(res)) {
                let genders = []
                for (var i = 0, length1 = res.length; i < length1; i++) {
                    let item = res[i]
                    genders.push({
                        value: item.value,
                        label: item.name
                    })
                }
                this.genders = genders
                let $table = this.$refs.xTable1
                if ($table) {
                    const genderNameColumn = $table.getColumnByField('genderName')
                    if (genderNameColumn) {
                        $table.setFilter(genderNameColumn, this.genders)
                    }
                }
            }
        })
    },
    watch: {
        $route: {
            // 路由监听
            deep: true,
            handler (newVar, oldVar) {
                // 显示列表、判断如果是添加页面或编辑页面回来刷新列表
                if (newVar.path === '/sys/user' && (oldVar.path === '/sys/user/add' || oldVar.path.indexOf('/sys/user/edit') >
                    -1 || oldVar.path.indexOf('/sys/user/roles') > -1)) {
                    this.showAddOrEdit = false
                    // this.filterData = {}// 将筛选数据置为空
                    if (this.$route.query.action !== 'back') {
                        // 不是返回才刷新列表
                        this.loadData()
                    }
                }
            }
        }
    },
    methods: {
        loadData () {
            let data = {
                pageNumber: this.tablePage.currentPage,
                pageSize: this.tablePage.pageSize,
                sortName: this.tablePage.sortName,
                sortOrder: this.tablePage.sortOrder,
                searchText: this.tablePage.searchText
            }
            data = Object.assign(data, this.filterData) // 合并请求测试
            this.loading = true
            this.$request.get(this.$apiSys.userListUrl, data).then(res => {
                this.list = res.rows
                this.tablePage.totalResult = res.total
                this.loading = false
            }, err => {
                this.loading = false
            })
        },
        handlePageChange (pageInfo) {
            this.tablePage.currentPage = pageInfo.currentPage
            this.tablePage.pageSize = pageInfo.pageSize
            this.loadData()
        },
        sortChangeEvent4 ({column, property, order}) {
            // 用户点击排序，参数：列信息、列属性名、排序方式（asc、desc、null）
            if (order == null) {
                // 用户取消排序，用默认排序，暂时先考虑单列排序，不考虑多列排序的情况
                this.tablePage.sortName = 'id'
                this.tablePage.sortOrder = 'desc'
            } else {
                this.tablePage.sortName = property
                this.tablePage.sortOrder = order
            }
            this.loadData()
        },
        filterChangeEvent ({column, property, values, datas, filterList, $event}) {
            // 用户点击筛选，参数：当前筛选列信息、当前筛选列属性名、当前筛选列值（checkbox）、当前筛选列值（input）、所有的筛选条件的信息
            // filterList 当筛选为输入框时，要从filterList[index].datas[0]中获取，获取的值是字符串了
            // filterList 当筛选为多选框时，要从filterList[index].values中获取，获取的是数组，在后台API中要注意
            let obj = {}
            for (var i = 0, length1 = filterList.length; i < length1; i++) {
                let item = filterList[i]
                if (item.property === 'name' || item.property === 'nick') {
                    obj[item.property] = item.datas[0]
                } else if (item.property === 'genderName') {
                    obj['gender'] = item.values
                } else if (item.property === 'roleName') {
                    obj['roleIds'] = item.values
                }
            }
            this.filterData = obj
            this.tablePage.currentPage = 1 // 回到第一页
            this.loadData()
        },
        formatterTime (arg) {
            return arg.cellValue !== null ? arg.cellValue.replace('T', ' ') : arg.cellValue
        },
        edit (id = 0) {
            if (id < 1) {
                let obj = this.$refs.xTable1.getCheckboxRecords()
                if (obj.length !== 1) {
                    this.$XModal.message({
                        content: '选择一行数据编辑',
                        status: 'error'
                    })
                    return false
                }
                id = obj[0].id
            }

            try {
                this.$router.push('/sys/user/edit/' + id)
                this.showAddOrEdit = true
            } catch (e) {
                console.log(e)
            }
        },
        searchTextChange () {
            this.tablePage.currentPage = 1
            this.loadData()
        },
        del () {
            let obj = this.$refs.xTable1.getCheckboxRecords()
            if (obj.length < 1) {
                this.$XModal.message({
                    content: '请选择要删除的用户',
                    status: 'error'
                })
                return false
            }
            let ids = []
            for (var i = 0; i < obj.length; i++) {
                ids.push(obj[i].id)
            }
            this.$request.delete(this.$apiSys.userDeleteUrl, {
                ids: ids + ''
            }, true).then(res => {
                if (res.status) {
                    this.$XModal.message({
                        content: res.msg,
                        status: 'success'
                    })
                    this.loadData()
                }
            })
        },
        refreshQuery () {
            console.log('refreshQuery')
        },
        role (id = 0) {
            if (id < 1) {
                let obj = this.$refs.xTable1.getCheckboxRecords()
                if (obj.length !== 1) {
                    this.$XModal.message({
                        content: '请先选择一条数据',
                        status: 'error'
                    })
                    return false
                }
                id = obj[0].id
            }

            try {
                this.$router.push('/sys/user/roles/' + id)
                this.showAddOrEdit = true
            } catch (e) {
                console.log(e)
            }
        }
    }
}
</script>
<style>
</style>
